package com.nulldev.util.web.nCaptcha.captchas.auto;

import java.io.InputStream;
import java.util.HashMap;

import com.nulldev.util.crypto.encryptAPI.XXTEA;
import com.nulldev.util.io.FileUtil;
import com.nulldev.util.java.DataSet;
import com.nulldev.util.lang.json.JsonObject;
import com.nulldev.util.uri.server.RequestType;
import com.nulldev.util.uri.server.v2.HttpPage2;
import com.nulldev.util.web.nCaptcha.backend.user.User;
import com.nulldev.util.web.nCaptcha.backend.user.UserManager;

public class RequestAutoCaptchaPayload extends HttpPage2 {

	public RequestAutoCaptchaPayload() {
		super("/auto_request");
	}

	public static final byte[] PAYLOAD_BYTES = 
			FileUtil.getResourceBytes(RequestAutoCaptchaPayload.class, "payload.js");

	@Override
	public DataSet<Integer, InputStream> request(RequestType type, String url, HashMap<String, String> headers,
			byte[] extraData, String ip) {
		final User user = UserManager.registerOrLoadUser(ip);
		final JsonObject obj = new JsonObject();
		obj.add("payload", XXTEA.encryptToBase64String(PAYLOAD_BYTES, user.key()));
		obj.add("uid", user.getUID());
		obj.add("key", user.key());
		return new DataSet<Integer, InputStream>(200, createStream(obj.toString()));
	}
}
